package com.tai.cobrapp.activity.crud;

import com.tai.cobrapp.R;
import com.tai.cobrapp.activity.LoginActivity;
import com.tai.cobrapp.activity.OptionsMenuActivity;
import com.tai.cobrapp.adapter.DeviceListAdapter;
import com.tai.cobrapp.backend.Backend;
import com.tai.cobrapp.model.Dispositivo;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView.OnItemLongClickListener;

public class EditDevicesActivity extends ListActivity{
	private final static int EDIT_DEVICE_DIALOG = 1;
	private final static int EDIT_DEVICE_ITEM_DIALOG = 2;
	private final static int YA_EXISTE_DISPOSITIVO = 3;
	private final static int COMPLETE_CAMPO_NAME = 4;
	private final static int DISPOSITIVO_GUARDADO = 5;

	DeviceListAdapter adapter = null;
	Dispositivo deviceItem = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list_devices);
		
		Integer idEstab = null;
		if( this.getIntent().getExtras() != null ){
			idEstab = this.getIntent().getExtras().getInt("idEstablecimiento");
		}
		adapter = new DeviceListAdapter(this, Backend.getInstance().getDispositivos(idEstab, this.getListView().getContext()));
		this.getListView().setAdapter(adapter);
		
		this.getListView().setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				// Agregar Custom Dialog para pedir lo necesario del dispositivo, luego cambiar los colores del item, vendido o no, etc
				//detalleAuxiliar = ((DetalleRelevamiento)adapter.getItem(position));
				//detalleListPosition = position;
				deviceItem = (Dispositivo)adapter.getItem(position);
				
				showDialog(EDIT_DEVICE_DIALOG);
				return false;
			}
		});
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialogo;
		Dialog dialogoEditDevice;
		
		switch(id){
		case EDIT_DEVICE_DIALOG:
			dialogo = new Dialog(this);
			dialogo.setContentView(R.layout.edit_device_dialog);
			dialogo.setTitle(R.string.establishment_options);
			
			android.view.WindowManager.LayoutParams params = dialogo.getWindow().getAttributes();
			params.width = LayoutParams.MATCH_PARENT;
			params.height = LayoutParams.MATCH_PARENT;
			dialogo.getWindow().setAttributes(params);

			Button editDeviceBtn = (Button)dialogo.findViewById(R.id.edit_device_item_btn);
			Button deleteDeviceBtn = (Button)dialogo.findViewById(R.id.delete_device_item_btn);
			Button cancelBtn = (Button)dialogo.findViewById(R.id.cancel_estab_btn);
			//final CheckBox fueVendido = (CheckBox)dialogo.findViewById(R.id.fue_vendido_chkbox);
//			Context _this = this;
			android.view.View.OnClickListener editarDevicesListener = new Button.OnClickListener() {
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_DEVICE_DIALOG);
					showDialog(EDIT_DEVICE_ITEM_DIALOG);
				}
			};
			android.view.View.OnClickListener deleteDeviceListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_DEVICE_DIALOG);
					AlertDialog.Builder builder = new AlertDialog.Builder(EditDevicesActivity.this);
			        builder.setMessage(R.string.sure_change_state)
			               .setPositiveButton(R.string.accept, new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {
			                	   // borrar el establecimiento
			                	   deviceItem.setActive(!deviceItem.isActive());
			                	   actualizarDispositivo(deviceItem);
			                	   adapter.notifyDataSetChanged();
			                   }
			               })
			               .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			                   public void onClick(DialogInterface dialog, int id) {
			                       // User cancelled the dialog
			                   }
			               });
			        builder.create().show();
				}
			};
			
			android.view.View.OnClickListener cancelarListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_DEVICE_DIALOG);
				}
			};
			editDeviceBtn.setOnClickListener(editarDevicesListener);
			deleteDeviceBtn.setOnClickListener(deleteDeviceListener);
			cancelBtn.setOnClickListener(cancelarListener);
			return dialogo;
		case EDIT_DEVICE_ITEM_DIALOG:
			dialogoEditDevice = new Dialog(this);
			dialogoEditDevice.setContentView(R.layout.edit_establish_or_device_item_dialog);
			dialogoEditDevice.setTitle(R.string.edit_device);
			
			android.view.WindowManager.LayoutParams paramsEditItem = dialogoEditDevice.getWindow().getAttributes();
			paramsEditItem.width = LayoutParams.MATCH_PARENT;
			paramsEditItem.height = LayoutParams.MATCH_PARENT;
			dialogoEditDevice.getWindow().setAttributes(paramsEditItem);
			
			final EditText deviceEditName = (EditText)dialogoEditDevice.findViewById(R.id.name);
			final EditText deviceEditDesc = (EditText)dialogoEditDevice.findViewById(R.id.description);
			Button saveEditBtn = (Button)dialogoEditDevice.findViewById(R.id.save_btn);
			Button cancelEditBtn = (Button)dialogoEditDevice.findViewById(R.id.cancel_btn);
			
			deviceEditName.setText(deviceItem.getName());
			deviceEditDesc.setText(deviceItem.getDescription());
			
			android.view.View.OnClickListener saveItemListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					if(deviceEditName.getText().toString() == null || deviceEditName.getText().toString().isEmpty() ){
						warningMessage(COMPLETE_CAMPO_NAME, null);
						return;
					}else if(existeOtroDevice(deviceItem.getName(), deviceEditName.getText())){
						warningMessage(YA_EXISTE_DISPOSITIVO, deviceEditName.getText().toString());
						deviceEditName.setText("");
						return;
					}else{
						deviceItem.setName(deviceEditName.getText());
						deviceItem.setDescription(deviceEditDesc.getText());
						actualizarDispositivo(deviceItem);
						adapter.notifyDataSetChanged();
						warningMessage(DISPOSITIVO_GUARDADO, deviceEditName.getText().toString());
						dismissDialog(EDIT_DEVICE_ITEM_DIALOG);
					}
				}
			};
			android.view.View.OnClickListener cancelItemListener = new Button.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dismissDialog(EDIT_DEVICE_ITEM_DIALOG);
				}
			};
			
			saveEditBtn.setOnClickListener(saveItemListener);
			cancelEditBtn.setOnClickListener(cancelItemListener);
			return dialogoEditDevice;
		default:
			return super.onCreateDialog(id);
		}
		
	}
	private void warningMessage(Integer message, String name){
		switch (message) {
		case COMPLETE_CAMPO_NAME:
			Toast.makeText(this, this.getString(R.string.fields_incomplete) + ": " + this.getString(R.string.name), Toast.LENGTH_SHORT).show();
			break;
		case YA_EXISTE_DISPOSITIVO:
			Toast.makeText(this, name + " " + this.getString(R.string.device_already_exists), Toast.LENGTH_SHORT).show();
			break;
		case DISPOSITIVO_GUARDADO:
			Toast.makeText(this, this.getString(R.string.device_edited_successful) + ": " + name, Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
	}
	public boolean existeOtroDevice(Editable nombreBase, Editable device){
		return Backend.getInstance().existeOtroDispositivo(this, nombreBase, device);
	}
	private void actualizarDispositivo(Dispositivo device){
		Backend.getInstance().updateDevice(this, device);
	}
	@Override
	public void onBackPressed() {
		Intent i = new Intent(EditDevicesActivity.this, EditEstablishmentsActivity.class);
		startActivity(i);
		super.onBackPressed();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}
	@Override
	protected void onStop() {
		finish();
		super.onStop();
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch(item.getItemId()){
		case R.id.main_menu:
			Intent i = new Intent(this, OptionsMenuActivity.class);
			startActivity(i);
			break;
		case R.id.log_out:
			Intent i2 = new Intent(this, LoginActivity.class);
			startActivity(i2);
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
}
